/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.joyz.api.result.i18n;

import io.gitee.joyz.api.result.logging.Log;
import io.gitee.joyz.api.result.logging.LogFactory;
import io.gitee.joyz.api.result.util.ObjectUtils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author JoyZ
 */
public abstract class MessageFormatSupport {

    private final Log log = LogFactory.getLogger(getClass());

    private final Map<String, Map<Locale, MessageFormat>> cachedMessageFormats = new HashMap<>(2);

    /**
     * 解析消息参数的模板方法. 如果需要解析复杂类型参数可在子类重写该方法.
     *
     * @param arguments 消息参数
     * @return 处理后的对象数组
     */
    protected Object[] resolveArguments(Object[] arguments) {
        return (arguments != null) ? arguments : new Object[0];
    }

    /**
     * 格式化文本, 并将 MessageFormat 组件缓存.
     *
     * @param pattern   消息文本
     * @param arguments 消息参数
     * @param locale    语言环境
     * @return 返回一个格式化后的消息文本, 如果抛出异常, 则会将传参 pattern 作为消息文本返回, 并且不带参数
     * @throws IllegalArgumentException 当消息格式化不成功时抛出该异常
     */
    public String format(String pattern, Object[] arguments, Locale locale) {
        if (!ObjectUtils.hasText(pattern)) {
            return pattern;
        }

        if (ObjectUtils.isEmpty(arguments)) {
            return pattern;
        }

        if (locale == null) {
            locale = Locale.getDefault();
        }

        MessageFormat messageFormat = null;

        synchronized (cachedMessageFormats) {

            Map<Locale, MessageFormat> localeMap = this.cachedMessageFormats.get(pattern);

            if (localeMap != null) {
                messageFormat = localeMap.get(locale);
            } else {
                localeMap = new HashMap<>(2);
                this.cachedMessageFormats.put(pattern, localeMap);
            }

            if (messageFormat == null) {

                try {
                    messageFormat = new MessageFormat(pattern, locale);

                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage() + " Pattern: '" + pattern + "'");
                    return pattern;
                }

                localeMap.put(locale, messageFormat);
            }
        }

        synchronized (messageFormat) {
            return messageFormat.format(resolveArguments(arguments));
        }
    }

    /**
     * 根据给定 message, locale 创建 {@link MessageFormat} 实例
     *
     * @param message 消息
     * @param locale  语言环境
     * @return 返回创建的 {@link MessageFormat} 实例
     */
    protected MessageFormat createMessageFormat(String message, Locale locale) {
        return new MessageFormat(message, locale);
    }
}
